<template>
  <div>
    <el-card class="box-card card-size">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="全部" name="0"/>
        <el-tab-pane
          :key="index"
          v-for="(item, index) in typeList"
          :label="item.typeName"
          :name="item.id.toString()">
        </el-tab-pane>
      </el-tabs>
      <span class="btn-box">
        <el-button class="view-btn" @click="handleView" type="primary" size="mini" :icon="icon"></el-button>
        <el-button class="add-btn" @click="handleAdd" type="primary" size="mini">新增</el-button>
        <el-popover class="search-btn" placement="bottom" title="搜索" width="400" trigger="click">
          <el-form ref="searchForm" :model="searchForm" label-width="80px">
            <el-form-item label="设备类型" size="mini" prop="typeName">
              <el-input v-model="searchForm.typeName"></el-input>
            </el-form-item>
            <el-form-item label="设备名称" size="mini" prop="deviceName">
              <el-input v-model="searchForm.deviceName"></el-input>
            </el-form-item>
            <el-form-item label="设备编号" size="mini" prop="deviceNo">
              <el-input v-model="searchForm.deviceNo"></el-input>
            </el-form-item>
            <el-form-item label="设备厂商" size="mini" prop="deviceMaker">
              <el-input v-model="searchForm.deviceMaker"></el-input>
            </el-form-item>
            <el-form-item label="节点类型" size="mini" prop="nodeType">
              <el-input v-model="searchForm.nodeType"></el-input>
            </el-form-item>
            <el-form-item label="所属" size="mini" prop="company">
              <el-input v-model="searchForm.company"></el-input>
            </el-form-item>
            <el-form-item label="状态" size="mini" prop="checkedStatus">
              <el-checkbox v-model="checkAll" label="全部" :indeterminate="isIndeterminate" @change="handleCheckAllChange"/>
              <el-checkbox-group v-model="checkedStatus" @change="handleCheckedStatusChange">
                <el-checkbox class="checkbox-box" v-for="(status, index) in statusList" :key="index" :label="status.value">
                  {{ status.label }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item style="margin-top: -30px">
              <el-button size="mini" type="primary" @click="fetchData">过 滤</el-button>
              <el-button size="mini" @click="resetSearch">重 置</el-button>
            </el-form-item>
          </el-form>
          <el-button slot="reference" style="margin-left: 10px" type="primary" size="mini" icon="el-icon-search"></el-button>
        </el-popover>
      </span>
    </el-card>
    <!--  echarts  -->
    <el-card class="box-card">
      <el-row>
        <el-col :span="12">
          <div id="chart" style="width: 600px; height: 260px;"></div>
        </el-col>
        <el-col :span="12">
          <el-row>
            <el-col :span="6" v-for="(item, index) in retData" style="margin-top: 60px">
              <el-statistic
                :value="item.value"
                :title="item.name">
              </el-statistic>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6" v-for="(item, index) in retData" style="margin-top: 60px">
              <el-statistic
                :precision="2"
                :value="item.value === 0 ? 0 : (item.value/retData[0].value) * 100"
                title="占比">
                <i slot="suffix">%</i>
              </el-statistic>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </el-card>
    <!--  table  -->
    <el-card class="box-card">
      <span>设备列表</span>
      <el-table v-loading="loading" :data="tableData"  @selection-change="handleSelectionChange" stripe style="width: 100%">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="编号" width="80" align="center"></el-table-column>
        <el-table-column prop="typeName" label="设备类型" width="130" align="center"></el-table-column>
        <el-table-column prop="deviceName" label="设备名称" width="130" align="center"></el-table-column>
        <el-table-column prop="deviceNo" label="设备编号" width="130" align="center"></el-table-column>
        <el-table-column prop="deviceMaker" label="设备厂商" width="130" align="center"></el-table-column>
        <el-table-column prop="status" label="设备状态" width="120" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 0 ? 'danger' : scope.row.status === 1 ? 'success' : scope.row.status === 2 ? 'info': null">
              {{scope.row.status === 0 ? '禁用' : scope.row.status === 1 ? '在线' : scope.row.status === 2 ? '离线' : null}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="nodeType" label="节点类型" width="130" align="center"></el-table-column>
        <el-table-column prop="company" label="所属" width="130" align="center"></el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleDetail(scope.row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>

    <el-dialog :title="title" :visible.sync="open" width="40%" @close="cancel">
      <el-form :model="form" ref="form" :rules="formRules">
        <el-form-item label="设备类型" label-width="100px" prop="tid">
          <el-select v-model="form.tid" placeholder="请选择设备类型">
            <el-option v-for="item in typeList"
                       :label="item.typeName"
                       :value="item.id"
                       :disabled="!item.status"></el-option>
            <el-option :value="undefined" disabled style="cursor: pointer;">
              <el-button type="text" @click="addDeviceType">
                <i class="el-icon-plus"></i> 添加
              </el-button>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备名称" label-width="100px" prop="deviceName">
          <el-input v-model="form.deviceName" autocomplete="off" placeholder="请输入设备名称"></el-input>
        </el-form-item>
        <el-form-item label="设备厂商" label-width="100px" prop="deviceMaker">
          <el-input v-model="form.deviceMaker" autocomplete="off" placeholder="请输入设备厂商"></el-input>
        </el-form-item>
        <el-form-item label="设备状态" label-width="100px" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">在线</el-radio>
            <el-radio :label="2">离线</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="节点类型" label-width="100px" prop="nodeType">
          <el-input v-model="form.nodeType" autocomplete="off" placeholder="请输入节点类型"></el-input>
        </el-form-item>
        <el-form-item label="所属" label-width="100px" prop="company">
          <el-input v-model="form.company" autocomplete="off" placeholder="请输入所属公司"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="onSubmit">提 交</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="openType" width="40%" @close="cancel">
      <el-form :model="typeForm" ref="typeForm" :rules="typeFormRules">
        <el-form-item label="类型名称" label-width="100px" prop="typeName">
          <el-input v-model="typeForm.typeName" autocomplete="off" placeholder="请输入类型名称"></el-input>
        </el-form-item>
        <el-form-item label="类型状态" label-width="100px" prop="status">
          <el-radio-group v-model="typeForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="onSubmit">提 交</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {getDeviceList, getTypeList, addDevice, addDeviceType, getStatusEcharts} from "@/api/device";
import * as echarts from 'echarts'
export default {
  data() {
    return {
      loading: true,
      activeName: this.$route.query.activeName || '1',
      typeList: [],
      tableData: [],
      pageNum: 1,
      pageSize: 5,
      total: 0,
      tid: 0,
      open: false,
      title: '',
      form: {},
      formRules: {
        tid: [
          { required: true, message: '请选择设备类型', trigger: 'change' }
        ],
        deviceName: [
          { required: true, message: '请输入设备名称', trigger: 'blur' }
        ],
        deviceMaker: [
          { required: true, message: '请输入设备厂商', trigger: 'blur' }
        ],
        status : [
          { required: true, message: '请选择设备状态', trigger: 'change' },
        ],
        nodeType: [
          { required: true, message: '请输入节点类型', trigger: 'blur' }
        ],
        company: [
          { required: true, message: '请输入所属公司', trigger: 'blur' }
        ],
      },
      typeForm: {},
      typeFormRules: {
        typeName: [
          { required: true, message: '请输入类型名称', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择类型状态', trigger: 'change' }
        ],
      },
      openType: false,
      isIndeterminate: false,
      checkAll: false,
      checkedStatus: [],
      statusList: [
        {
          value: 1,
          label: '在线'
        },
        {
          value: 2,
          label: '离线'
        },
        {
          value: 0,
          label: '禁用'
        }
      ],
      searchForm: {},
      retData: [],
      icon: 'el-icon-monitor'
    };
  },
  created() {
    this.findType();
    // this.fetchData();
  },
  mounted() {
    this.handleClick()
    this.initEcharts()
  },
  methods: {
    findType() {
      getTypeList().then(res => {
        this.typeList = res.data;
      })
    },
    fetchData() {
      let params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        tid: this.tid,
        ...this.searchForm,
        statusList: this.checkedStatus.length > 0 ? this.checkedStatus.join(',') : null
      }
      this.loading = true;
      getDeviceList(params).then(res => {
        this.tableData = res.data.dataList;
        this.total = res.data.total;
        this.loading = false;
      })
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.fetchData();
    },
    handleClick() {
      this.tid = this.activeName;
      this.fetchData();
      this.initEcharts()
    },
    handleSelectionChange() {},
    handleDetail(row) {
      this.$router.push({
        path: '/device/detail',
        query: {
          types: this.typeList,
          activeName: this.activeName,
          rows: row,
        }
      })
    },
    handleAdd() {
      this.title = '新增设备';
      this.open = true;
      this.form = {
        status: 1
      }
    },
    onSubmit() {
      if (this.title === '新增设备') {
        this.$refs.form.validate((valid) => {
          if (valid) {
            addDevice(this.form).then(res => {
              this.$message({
                message: '添加成功',
                type: 'success',
                duration: 1000
              });
              this.open = false;
              this.fetchData();
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      } else if (this.title === '新增设备类型') {
        this.$refs.typeForm.validate((valid) => {
          if (valid) {
            addDeviceType(this.typeForm).then(res => {
              this.$message({
                message: '添加成功',
                type: 'success',
                duration: 1000
              });
              this.openType = false;
              this.findType();
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      }

    },
    addDeviceType() {
      this.title = '新增设备类型';
      this.openType = true;
      this.typeForm = {
        status: 1
      };
    },
    handleCheckedStatusChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.statusList.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.statusList.length;
    },
    handleCheckAllChange(val) {
      if(this.checkAll){
        this.checkedStatus = this.statusList.map(item => item.value)
        this.isIndeterminate = false;
      }else {
        this.checkedStatus = []
      }
    },
    cancel() {
      if (this.title === '新增设备') {
        this.reset();
        this.open = false;
      } else if (this.title === '新增设备类型') {
        this.reset();
        this.openType = false;
      }
    },
    resetSearch() {
      this.reset()
      this.checkedStatus = []
      this.isIndeterminate = false
      this.checkAll = false
      this.fetchData()
    },
    initEcharts() {
      // 初始化
      const chart = echarts.init(document.getElementById('chart'))
      getStatusEcharts({tid: this.tid}).then(res => {
        this.retData = res.data;

        const options = {
          title: {
            text: '设备数据分析'
          },
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            data: ['数量']
          },
          xAxis: {
            data: this.retData.map(item => item.name)   // 从后端获得x轴展示内容
          },
          yAxis: {
          },
          series: [
            {
              colorBy:'data',
              name: '数量',
              type: 'bar',
              data: this.retData.map(item => item.value),  // 从后端获得y轴展示数据
              barWidth: '25%',
            }
          ]
        }
        // 使用图表配置
        chart.setOption(options)
      })
    },
    reset() {
      if (this.title === '新增设备') {
        this.form = {};
        this.resetForm("form")
      } else if (this.title === '新增设备类型') {
        this.typeForm = {};
        this.resetForm("typeForm")
      } else {
        this.searchForm = {};
        this.resetForm("searchForm")
      }
    },
    resetForm(formName) {
      this.$nextTick(() => {
        this.$refs[formName].clearValidate();
      })
    },
    handleView() {
      this.icon = this.icon === 'el-icon-monitor' ? 'el-icon-s-operation' : 'el-icon-monitor';
    }
  }
};
</script>

<style scoped>
.box-card {
  margin: 20px;
}
.card-size {
  height: 75px;
}
.el-tabs {
  margin-top: -10px;
  width: 86%;
}
.el-pagination {
  float: right;
  margin: 20px 0 20px 0;
}
.btn-box {
  float: right;
}
.view-btn, .add-btn, .search-btn {
  position: relative;
  bottom: 35px;
  left: 10px;
}
.el-select {
  width: 90%;
}
.el-input {
  width: 90%;
}
.el-popover {
  position: relative;
}
.checkbox-box {
  position: relative;
  left: 75px;
  top: -28px;
}
</style>
